﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Moon.Sql
{
    internal class DefaultBatchImpl : IBatch
    {
        protected List<object> batchs = null;

        public DefaultBatchImpl()
        {
            batchs = new List<object>();
        }

        private void Clear()
        {
            batchs.Clear();
            batchs = null;
        }

        public void AttachDeleteable<T>(IDeleteable<T> deleteable)
        {
            batchs.Add(deleteable);
        }
        public void AttachInsertable<T>(IInsertable<T> insertable)
        {
            batchs.Add(insertable);
        }
        public void AttachUpdateable<T>(IUpdateable<T> updateable)
        {
            batchs.Add(updateable);
        }

        public virtual int Execute()
        {
            int count = 0;
            foreach (var item in batchs)
            {
                count += Convert.ToInt32(item.GetType().GetMethod("Execute").Invoke(item, null));
            }
            Clear();
            return count;
        }

        public virtual async Task<int> ExecuteAsync()
        {
            int count = 0;
            foreach (var item in batchs)
            {
                var methodObj = item.GetType().GetMethod("ExecuteAsync");
                Task task = methodObj.Invoke(item, null) as Task;
                await task;
                count += Convert.ToInt32(task.GetType().GetProperty("Result").GetValue(task, null));
            }
            Clear();
            return count;
        }
    }
}
